package com.sky.service.impl;

import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSON;
import com.sky.dto.UserLoginDTO;
import com.sky.entity.User;
import com.sky.exception.BusinessException;
import com.sky.mapper.UserMapper;
import com.sky.properties.WeChatProperties;
import com.sky.service.UserService;
import com.sky.utils.HttpClientUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.Map;

@Service
public class UserServiceImpl implements UserService {



    //登录
    @Autowired
    private UserMapper userMapper;

    @Autowired
    private WeChatProperties weChatProperties;



    @Override
    public User login(UserLoginDTO userLoginDTO) {
        //1. 向微信平台发送请求,获取openid
        //1-1 准备URL
        String url = "https://api.weixin.qq.com/sns/jscode2session";
        //1-2 准备请求参数
        Map<String, String> paramMap = new HashMap<>();
        paramMap.put("appid", weChatProperties.getAppid());
        paramMap.put("secret", weChatProperties.getSecret());
        paramMap.put("js_code", userLoginDTO.getCode());
        paramMap.put("grant_type", "authorization_code");
        //1-3 发送请求
        String json = HttpClientUtil.doGet(url, paramMap);
        //1-4 获取返回结果
        Map<String, Object> map = JSON.parseObject(json, Map.class);
        String openid = (String) map.get("openid");
        //1-5 判断
        if (StrUtil.isEmpty(openid)) {
            throw new BusinessException("微信登录失败");
        }

        //2. 根据openid从user表中进行查询,如果查不到,代表是新用户,需要保存到表中
        User user = userMapper.findByOpenid(openid);
        if (user == null){
            //2-1查不到,代表是新用户
            user = User.builder()
                    .openid(openid)
                    .createTime(LocalDateTime.now())
                    .build();

            //2-2 需要保存到表中(要主键返回)
            userMapper.save(user);
        }

        //3. 返回user
        return user;
    }
}
